package com.example.anydo.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.anydo.R;
import com.example.anydo.adapter.TaskAdapter;
import com.example.anydo.bean.SubTaskBean;
import com.example.anydo.bean.TaskBean;
import com.example.anydo.service.TimeTaskService;
import com.example.anydo.util.database.DatabaseHelper;
import com.example.anydo.util.pub_util.SPUtil;
import com.example.anydo.util.pub_util.Synchronizer;
import com.example.anydo.util.pub_util.Util;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private TabLayout tabLayoutDate;
    private RecyclerView recyclerViewTaskList;

    private int userId;

    private TabLayout.Tab[] tabs;

    private ImageView img_todoBox;
    private ImageView img_newItem;
    private ImageView img_syncToCloud;
    private ImageView img_logo;
    private TextView txt_fullDate;
    private TextView txt_username;
    private DatabaseHelper dbHelper;
    private ArrayList<TaskBean> taskBeanList = new ArrayList<>();
    private TaskAdapter taskAdapter;
    private Synchronizer synchronizer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //  开始提醒服务
        Intent intent = new Intent(this, TimeTaskService.class);
        startService(intent);


        userId = Integer.parseInt(SPUtil.getUserId(this));
        dbHelper = new DatabaseHelper(this);
        synchronizer = new Synchronizer(this);

        initView();

        initSettings();


        String today = Util.getDayNow();
        tabLayoutDate.selectTab(tabs[Integer.parseInt(today.substring(6))-1]);

    }

    @Override
    protected void onResume() {
        super.onResume();
        String today = Util.getDayNow();
        freshData(today);
        tabLayoutDate.selectTab(tabs[Integer.parseInt(today.substring(6))-1]);
    }

    /**
     * 为各控件初始化数据
     */
    private void freshData(String day){

        taskBeanList = dbHelper.getTasksOfDay(userId,day);
        if(taskBeanList == null){
            taskBeanList = new ArrayList<>();
        }
        //taskAdapter.notifyDataSetChanged();
        taskAdapter.freshData(taskBeanList);
    }

    private void initSettings() {
        taskAdapter = new TaskAdapter(taskBeanList, this);
        recyclerViewTaskList.setAdapter(taskAdapter);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerViewTaskList.setLayoutManager(layoutManager);
        recyclerViewTaskList.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.img_logo:
            case R.id.txt_fullDate:
            case R.id.txt_username:

                // 跳转到用户信息界面
                intent = new Intent(this,PersonInfoActivity.class);
                startActivity(intent);
                break;

            case R.id.img_todoBox:
                // 跳转到待办箱界面
                intent = new Intent(this, CollectionActivity.class);
                startActivity(intent);
                break;
            case R.id.img_syncToCloud:
                //  同步
                Util.toast(this,"数据同步");

                synchronizer.postData(userId);
                break;

            case R.id.img_newItem:
                // 添加任务
                EditTaskActivity.actionStart(this,null,EditTaskActivity.SAVE_NEW);
                break;

        }
    }



    /**
     * 加载自定义Tab
     * @param whatDay 周几
     * @param day 年月日的日
     * @return tabView
     */
    private View makeTabView(String whatDay, int day){
        View tabView = LayoutInflater.from(this).inflate(R.layout.tab_item_date, null);
        TextView textWhatDay = tabView.findViewById(R.id.txt_whatDay);
        textWhatDay.setText(whatDay);
        TextView textDay = tabView.findViewById(R.id.txt_day);
        String str = "" + day;
        textDay.setText(str);
        return tabView;
    }

    /**
     * 根据日返回周几
     * @param day 日
     * @return 周几
     */
    private String getWhatDay(int day){
        String date = Util.getDayNow().substring(0,6);
        if(day<10){
            date += "0" + day;
        }else {
            date+=day;
        }
        day = Util.getWeekday(date);
        String res;
        switch (day){
            case 1:
                res = "周日";
                break;
            case 2:
                res = "周一";
                break;
            case 3:
                res = "周二";
                break;
            case 4:
                res = "周三";
                break;
            case 5:
                res = "周四";
                break;
            case 6:
                res = "周五";
                break;
            case 7:
                res = "周六";
                break;
            default:
                res = " ";
                break;
        }
        return res;
    }

    /**
     * 初始化各View
     */
    private void initView() {
        img_todoBox = findViewById(R.id.img_todoBox);
        tabLayoutDate = findViewById(R.id.tabLayout_date);
        img_newItem = findViewById(R.id.img_newItem);
        img_syncToCloud = findViewById(R.id.img_syncToCloud);
        img_logo = findViewById(R.id.img_logo);
        txt_fullDate = findViewById(R.id.txt_fullDate);
        txt_username = findViewById(R.id.txt_username);

        txt_username.setText(dbHelper.getUserNameById(userId));
        txt_fullDate.setText(Util.getDayNowShow());

        img_todoBox.setOnClickListener(this);
        img_newItem.setOnClickListener(this);
        img_syncToCloud.setOnClickListener(this);
        img_logo.setOnClickListener(this);
        txt_fullDate.setOnClickListener(this);
        txt_username.setOnClickListener(this);

        Calendar calendar = Calendar.getInstance();
        final int day = calendar.get(Calendar.DAY_OF_MONTH);
        int days = Util.getDaysOfMonth(Util.getDayNow());
        tabs = new TabLayout.Tab[days];

        for (int i = 1; i <= days; i++) {
            tabs[i-1] = tabLayoutDate.newTab();
            tabs[i-1].setCustomView(makeTabView(getWhatDay(i), i));
            if (i == day) {
                tabLayoutDate.addTab(tabs[i-1], true);
            } else {
                tabLayoutDate.addTab(tabs[i-1]);
            }
        }
        // tab滑动到所选日期的位置
        tabLayoutDate.post(new Runnable() {
            @Override
            public void run() {
                int x = 180 * (day - 1);
                tabLayoutDate.smoothScrollTo(x, 0);
            }
        });

        tabLayoutDate.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                View tabView = tab.getCustomView();
                assert tabView != null;
                TextView txtDay = tabView.findViewById(R.id.txt_day);
                String strDay = txtDay.getText().toString();


                String date = Util.getDayNow();
                String fullDate = date.substring(0,4) + "年"+
                        date.substring(4,6) + "月" +
                        strDay + "日";
                txt_fullDate.setText(fullDate);


                char[] dayC = strDay.toCharArray();
                char[] dateC = date.toCharArray();
                if(dayC.length == 1){
                    dateC[6] = '0';
                    dateC[7] = dayC[0];
                }else {
                    dateC[6] = dayC[0];
                    dateC[7] = dayC[1];
                }
                // 刷新数据
                freshData(new String(dateC));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        recyclerViewTaskList = findViewById(R.id.recycler_taskList);
    }



    private void makeData(){
        // TODO: 将此部分的死数据改成从数据库接口获取
        String TAG = "test";
        taskBeanList = new ArrayList<>();
        //第一个item
        TaskBean taskBean1 = new TaskBean();
        TaskBean.DataBean dataBean11 = new TaskBean.DataBean();
        dataBean11.setIfDone("是");
        dataBean11.setTitle("完成安卓作业");
        taskBean1.setData(dataBean11);
        //第二个item
        TaskBean taskBean2 = new TaskBean();
        TaskBean.DataBean dataBean21 = new TaskBean.DataBean();
        dataBean21.setIfDone("否");
        dataBean21.setTitle("完成课设作业1");
        dataBean21.setTime("12:00提醒");
        taskBean2.setData(dataBean21);
        //第三个item
        TaskBean taskBean3 = new TaskBean();
        TaskBean.DataBean dataBean31 = new TaskBean.DataBean();
        dataBean31.setIfDone("否");
        dataBean31.setTitle("每天晚上去跑步");
        dataBean31.setTime("12:00提醒");
        dataBean31.setRate(" ");
        taskBean3.setData(dataBean31);
        //第四个item
        TaskBean taskBean4 = new TaskBean();
        TaskBean.DataBean dataBean41 = new TaskBean.DataBean();
        dataBean41.setIfDone("否");
        dataBean41.setTitle("每天晚上去打篮球");
        dataBean41.setTime("12:00提醒");
        dataBean41.setRate(" ");
        ArrayList<SubTaskBean.DataBean> subDataList = new ArrayList<>();
        SubTaskBean.DataBean subDataBean1 = new SubTaskBean.DataBean();
        subDataBean1.setIfDone("否");
        subDataBean1.setTitle("准备活动1");
        subDataList.add(subDataBean1);
        SubTaskBean.DataBean subDataBean2 = new SubTaskBean.DataBean();
        subDataBean2.setIfDone("是");
        subDataBean2.setTitle("准备活动2");
        subDataList.add(subDataBean2);
        SubTaskBean.DataBean subDataBean3 = new SubTaskBean.DataBean();
        subDataBean3.setIfDone("否");
        subDataBean3.setTitle("准备活动3");
        subDataList.add(subDataBean3);
        dataBean41.setSubTasks(subDataList);
        taskBean4.setData(dataBean41);

        taskBeanList.add(taskBean1);
        taskBeanList.add(taskBean2);
        taskBeanList.add(taskBean3);
        taskBeanList.add(taskBean4);
    }


}